package com.heima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.thread.MyThreadLocal;
import com.heima.mapper.WmNewsMapper;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.media.dto.WmNewsPageReqDto;
import com.heima.model.media.pojos.WmNews;
import com.heima.service.WmNewsService;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    //查询所有文章
    @Override
    public PageResponseResult newsList(WmNewsPageReqDto dto) {
        if (dto.getPage() == null || dto.getSize() == null){
            return null;
        }
        // 定义分页对象
        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        // 定义分页条件
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery(WmNews.class)
                //状态
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                //开始时间
                //结束时间
                .between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null,
                        WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate())
                //所属频道ID
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())
                //关键字
                .like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword())
                //查询当前登录用户的文章
                .eq(WmNews::getUserId, MyThreadLocal.get())
                //发布时间倒序查询
                .orderByDesc(WmNews::getPublishTime);
        // 分页查询
        Page<WmNews> pages = this.page(page, wrapper);
        // 封装数据
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), ((int) pages.getTotal()));
        pageResponseResult.setData(pages.getRecords());
        // 返回结果
        return pageResponseResult;
    }
}
